#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QString>
#include <QFileInfo>
#include <QFileInfoList>
#include <QDir>
#include <QDirIterator>
#include <QDebug>
#include <QString>
#include <QRegularExpression>



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::removeStringFromFileName(const QString &fileName, const QString &pattern) {
    QString result = fileName;
    QRegularExpression regExp(pattern); // 创建正则表达式对象
    QRegularExpressionMatchIterator i = regExp.globalMatch(fileName);
    while (i.hasNext()) {
        QRegularExpressionMatch match = i.next();
        qDebug() << match.captured();

    }
    return result;
}

/**
 * @brief MainWindow::listFilesAndFolders
 * @param path
 */
void MainWindow::listFilesAndFolders(const QString &path) {
    QDir dir(path);
    // 获取文件和子目录的列表
    QStringList entries = dir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    // 迭代文件和子目录
    for (const QString &entry : entries) {
        QFileInfo fileInfo(dir.filePath(entry));
        if (fileInfo.isDir()) {
            qDebug() << "目录：" << fileInfo.absoluteFilePath();
            ui->plainTextEdit->appendPlainText(fileInfo.absoluteFilePath());
            // 如果你想递归地列出子目录中的文件，可以调用
            listFilesAndFolders(fileInfo.absoluteFilePath());
        } else if (fileInfo.isFile()) {
            qDebug() << "文件：" << fileInfo.absoluteFilePath();
            ui->plainTextEdit->appendPlainText("-"+fileInfo.absoluteFilePath());
        }
    }
}

// 打开文件目录
void MainWindow::on_pushButton_clicked()
{
    QString dirPath = QFileDialog::getExistingDirectory(this,"打开一个文件夹","D:\\WORK_SPACE\\learn-document");
    if(!dirPath.isEmpty())
    {
        ui->lineEdit->setText(dirPath);
    }
}

/**
 * 子文件夹
 * @brief MainWindow::on_pushButton_2_clicked
 */
void MainWindow::on_pushButton_2_clicked()
{
    QDir pdir(ui->lineEdit->text());
    QFileInfoList fileList = pdir.entryInfoList(QDir::NoDotAndDotDot |QDir::AllEntries);
    QListIterator<QFileInfo> it(fileList);
    while (it.hasNext()) {
        QFileInfo file = it.next();
        ui->plainTextEdit->appendPlainText(file.fileName());
    }
}

/**
 * 迭代
 * @brief MainWindow::on_pushButton_3_clicked
 */
void MainWindow::on_pushButton_3_clicked()
{
    ui->plainTextEdit->clear();
    QDir pdir(ui->lineEdit->text());
    QFileInfoList fileList = pdir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllDirs);
    QListIterator<QFileInfo> it(fileList);
    while (it.hasNext()) {
        QFileInfo file = it.next();
        ui->plainTextEdit->appendPlainText(file.fileName());
        listFilesAndFolders(file.absoluteFilePath());
    }
}

